/**
 * @BelongsProject: gene-mutation-timeyan-host
 * @BelongsPackage: cn.gene.timeyan.pay.webapi.service.impl
 * @Author: 吕易
 * @CreateTime: 2022-08-15  16:44
 * @Description: TODO
 * @Version: 1.0
 */
package cn.gene.timeyan.pay.webapi.service.impl;

import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.common.pojo.domain.TimeyanAuthenticationInfo;
import cn.gene.timeyan.common.restful.ResponseCode;
import cn.gene.timeyan.pay.service.IPointsExchangeService;
import cn.gene.timeyan.pay.service.OrderInfoService;
import cn.gene.timeyan.pay.service.ProductService;
import cn.gene.timeyan.pay.webapi.mapper.PointsExchangeMapper;
import cn.gene.timeyan.pojo.pay.enums.OrderStatus;
import cn.gene.timeyan.pojo.pay.enums.PayType;
import cn.gene.timeyan.pojo.pay.model.OrderInfo;
import cn.gene.timeyan.pojo.pay.model.PointsExchange;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class PointsExchangeServiceImpl extends ServiceImpl<PointsExchangeMapper, PointsExchange> implements IPointsExchangeService {
    @Resource
    private ProductService productService;

    @Resource
    private OrderInfoService orderInfoService;

    /**
     * 积分兑换
     */
    @DS("timeyan_user")
    @Override
    public void pointsExchange(Long goodsId,String address) {
//        Long userId = getUserId();
        //测试时使用
        Long userId = 1L;
        int score = getScore(userId);
        int price = productService.queryPriceById(goodsId);
        //一块钱换一积分
        if (score < price*100){
            throw new TimeyanServiceException(ResponseCode.BAD_REQUEST,"积分不足!");
        }
        log.info("生成订单...");
        OrderInfo orderInfo = orderInfoService.createOrderByProductId(goodsId, PayType.POINTSEXCHANGE.getType());
        log.info("更新用户积分...");
        QueryWrapper<PointsExchange> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        PointsExchange pointsExchange = new PointsExchange();
        pointsExchange.setScore(score - price*100);
        int row = baseMapper.update(pointsExchange, queryWrapper);
        if (row != 1){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"服务器繁忙,请稍后再试!");
        }
        log.info("更新订单状态...");
        //获取订单号
        String orderNo = orderInfo.getOrderNo();
        //更新订单状态
        orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.SUCCESS);
    }

    /**
     * 获取用户积分
     * @param userId
     * @return
     */
    public int getScore(Long userId){
        log.info("获取用户积分...");
        QueryWrapper<PointsExchange> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        PointsExchange pointsExchange = baseMapper.selectOne(queryWrapper);
        return pointsExchange.getScore();
    }

    public TimeyanAuthenticationInfo getUserInfo(){
        // 获得SpringSecurity容器对象
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder
                        .getContext().getAuthentication();
        // 判断获取的容器信息是否为空
        if (authenticationToken == null){
            throw new TimeyanServiceException(ResponseCode.UNAUTHORIZED,"没有登录信息!");
        }
        // 如果容器中有内容,证明当前容器中有登录用户信息
        // 我们获取这个用户信息并返回
        TimeyanAuthenticationInfo authenticationInfo =
                (TimeyanAuthenticationInfo) authenticationToken.getCredentials();
        return authenticationInfo;
    }

    // 业务逻辑层中大多数方法都是获得用户id,所以编写一个返回用户id的方法
    public Long getUserId(){
        return getUserInfo().getId();
    }
}

